<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <title data-i18n="detailTitle">车辆详情</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  
  <!-- 引入 Bootstrap 5 CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  
  <!-- 引入 Flatpickr CSS & JS -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
  <script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.js"></script>
  <!-- 多语言包（根据需要引入） -->
  <script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/zh.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/th.js"></script>
  
  <style>
    body {
      margin: 0; padding: 0;
      background-color: #007bff;
      font-family: Arial, sans-serif;
    }
    .back-btn {
      background: #eee;
      border: none;
      padding: 8px 12px;
      border-radius: 6px;
      font-size: 14px;
      cursor: pointer;
      margin-bottom: 15px;
    }
    .page-wrapper {
      width: 95%; max-width: 1200px;
      margin: 30px auto; background-color: #fff;
      border-radius: 15px; box-shadow: 0 6px 16px rgba(0,0,0,0.2);
      display: flex; flex-direction: row;
      position: relative; overflow: hidden;
    }
    .left-section {
      flex: 0 0 60%;
      display: flex;
      flex-direction: column; /* 改为垂直排列 */
      align-items: center;    /* 居中对齐 */
      justify-content: flex-start;
      padding: 20px;
    }

    #carImage {
      width: 150px;
      height: 150px;
      object-fit: cover;
      border-radius: 5px;
      margin-bottom: 15px;
    }

    /* 针对放在 #carImagesContainer 内的图片 */
    #carImagesContainer {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 10px;           /* 图片间距 */
      margin-top: 15px;
    }

    #carImagesContainer img {
      width: 100%;
      aspect-ratio: 1;    /* 保持正方形，可换成 4/3、16/9 …… */
      object-fit: cover;  /* 裁切溢出部分 */
      border-radius: 8px; /* 圆角 */
      box-shadow: 0 2px 6px rgba(0,0,0,0.2);
      transition: transform .2s;
      cursor: pointer;
    }

    #carImagesContainer img:hover {
      transform: scale(1.03);
    }
    
    .right-section {
      flex: 0 0 40%; min-width: 300px;
      padding: 20px 30px; display: flex;
      flex-direction: column; justify-content: center;
    }
    .car-title {
      font-size: 28px; font-weight: bold;
      margin-bottom: 20px; color: #333;
    }
    .price-info {
      font-size: 24px; line-height: 1.8; color: #333;
      margin-bottom: 20px;
    }
    .detail-box {
      width: 80%; margin: 0 auto 20px;
      background-color: #f5f5f5; border: 1px solid #ccc;
      border-radius: 8px; padding: 12px;
      font-size: 14px; color: #666; line-height: 1.6;
    }
    .info-line {
      margin-bottom: 1em;
      font-size: 18px; /* 这里可根据需要调大一些 */
      font-weight: normal; /* 如果需要更粗可以用 bold */
      color: #333;         /* 字体颜色 */
    
    }
    .info-line.rental-days {
      font-size: 20px;
    }
    .info-line.payable-price {
      font-size: 24px;
      font-weight: bold;
    }
    .info-line span {
      font-weight: bold; color: #333;
    }
    .modal-title {
      font-size: 20px;
      font-weight: bold;
    }
    .detail-label {
      font-weight: bold;
      color: #333;
      font-size: 1.1em; /* 调整为想要的字号 */
    }
    .detail-value {
      font-weight: normal;
      color: #555;
      margin-left: 8px;
    }
    .form-label {
      font-size: 16px;
    }
    .policy-container {
      max-width: 600px;
      margin: 0 auto;
      font-family: Arial, sans-serif;
      color: #333;
      line-height: 1.6;
    }

    .policy-section {
      margin-bottom: 20px;
    }

    .policy-title {
      font-size: 0.1em;
      font-weight: bold;
      margin-bottom: 8px;
    }

    .policy-text {
      margin-right: 20px;
      margin-left: 20px;
      font-size: 0.5em;
      margin-bottom: 4px;
    }

    .policy-detail {
      margin-right: 20px;
      margin-left: 20px;
      font-size: 0.5em;
      color: #666;
    }
    h2 {
      margin-right: 15px;
      margin-left: 15px;
      font-size: 1.1em;
      font-weight: bold;
      margin-bottom: 8px;
    }
    p {
      margin-right: 20px;
      margin-left: 20px;
      font-size: 0.8em;
      margin-bottom: 4px;
    }
    .next-btn {
      margin: 10px auto;
      width: 100%; padding: 12px;
      font-size: 16px; background-color: #007bff;
      color: #fff; border: none; border-radius: 5px;
      cursor: pointer;
    }
    .next-btn:hover {
      background-color: #0056c1;
    }
    #statusMsg {
      margin-top: 10px; font-size: 14px; color: #666;
    }
    /* Flatpickr 已被标记为 booked-day 的日期加红点 */
    .flatpickr-day.booked-day {
      position: relative;
    }
    .flatpickr-day.booked-day::after {
      content: "";
      position: absolute;
      top: 4px; right: 4px;
      width: 6px; height: 6px;
      background-color: red; border-radius: 50%;
      pointer-events: none;
    }
    @media (max-width: 768px) {
      .page-wrapper { flex-direction: column; }
      .left-section, .left-section img {
        width: 100%; max-width: none;
        margin: 0 auto; display: block;
      }
      .right-section { width: 100%; }
      .back-btn { position: static; margin: 10px; }
    }
    .thumbnail {
      cursor: pointer;
      max-width: 400px;
      border: 1px solid #ddd;
      border-radius: 5px;
      padding: 5px;
      background-color: #fff;
    }
    /* 遮罩层 */
    #zoomOverlay {
      display: none;
      position: fixed;
      top: 0; left: 0;
      width: 100%; height: 100%;
      background: rgba(0,0,0,0.8);
      justify-content: center;
      align-items: center;
      z-index: 9999;
    }
    #zoomOverlay img {
      max-width: 90%;
      max-height: 90%;
      object-fit: contain;
      border-radius: 10px;
    }
  </style>
</head>
<body>
  <!-- 返回按钮 -->
  <button class="back-btn" onclick="window.history.back()">← <span data-i18n="backButton">返回</button>
  
  <!-- 页面主体容器 -->
  <div class="page-wrapper">
    <!-- 左侧：车辆图片 -->
    <div class="left-section">
      <div id="carImagesContainer" class="image-grid mt-3"></div>
    </div>
    <div id="zoomOverlay" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background: rgba(0,0,0,0.8); justify-content: center; align-items: center; z-index: 9999;">
      <img id="zoomImage" src="" alt="Zoomed Image" style="max-width:90%; max-height:90%; object-fit: contain;">
    </div>
    <!-- 右侧：车辆信息 + 订单表单 -->
    <div class="right-section">
      <div class="car-title" id="carTitle" data-i18n="detailUnknownModel">未知车型</div>
      <div class="price-info mb-3">
        <p><span data-i18n="detailDailyPrice">日租：</span><span id="dailyPrice">---</span> ฿</span></p>
        <p><span data-i18n="detailWeeklyPrice">周租：</span><span id="weeklyPrice">---</span> ฿</span></p>
        <p><span data-i18n="detailMonthlyPrice">月租：</span><span id="monthlyPrice">---</span> ฿</span></p>
      </div>
      <div class="detail-box mb-3" id="carDetail">描述加载中...</div>
      <!-- 日期选择（type="text" 让 Flatpickr 接管） -->
      <div class="mb-3">
        <label for="startDate" class="form-label" data-i18n="detailPickDate">取车日期：</label>
        <input type="text" class="form-control" id="startDate" />
      </div>
      <div class="mb-3">
        <label for="endDate" class="form-label" data-i18n="detailReturnDate">还车日期：</label>
        <input type="text" class="form-control" id="endDate" />
      </div>
      <div class="info-line">
        <span data-i18n="detailRentalDays">租车天数：</span>
        <span id="daysInfo">0</span>
        <span data-i18n="daysSuffix">天</span>
      </div>
      <div class="info-line">
        <span data-i18n="detailPayablePrice">租金价格：</span>
        <span id="priceInfo">0</span> ฿</span>
      </div>
      <div class="info-line">
        <span data-i18n="depositLabel">押金价格：</span>
        <span id="depositInfo">0</span> ฿</span>
      </div>
<button class="next-btn" id="nextBtn" data-bs-toggle="modal" data-bs-target="#confirmModal" data-i18n="detailNextStep">下一步</button>      <div id="statusMsg"></div>
    </div>
  </div>

  <!-- Modal 弹窗 -->
  <div class="modal fade" id="confirmModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" data-i18n="confirmOrderTitle">确认订单</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <p><span class="detail-label" data-i18n="detailRentalDays">租车天数：</span>
            <span id="modalDays">0</span> <span data-i18n="daysSuffix">天</span></p>
          <p><span class="detail-label" data-i18n="detailPayablePrice">应付价格：</span>
            <span id="modalPrice">0</span> <span data-i18n="priceSuffix">THB</span></p>
          <p><span class="detail-label" data-i18n="depositLabel">应付价格：</span><span id="modalDeposit">0</span> 
            <span data-i18n="priceSuffix">THB</span></p>
          <div class="policy-container bg-light p-3 mb-3" style="border-radius: 5px;">
            <!-- 公司地址部分 -->
            <section class="policy-section">
              <h2 data-i18n="modalAddressTitle">公司地址：</h2>
              <p data-i18n="modalAddressText">888 Ratchadapisek Rd, Bangkok, Thailand</p>
              <p data-i18n="modalAddressDetail">客户可在上述地址办理取车及还车手续，请确保按时到达办理。</p>
            </section>
            <!-- 定金说明部分 -->
            <section class="policy-section">
              <h2 data-i18n="modalPolicyTitle">定金说明：</h2>
              <p data-i18n="modalPolicyText">若需取消或修改订单，请务必在取车前至少 3 天通知我们。</p>
              <p data-i18n="modalPolicyDetail">如果在距离取车不足 3 天内取消或修改订单，系统将仅退回 20% 的定金，其余费用不予退还。</p>
            </section>
            <!-- 送车费部分 -->
            <section class="policy-section">
              <h2 data-i18n="modalDeliveryFeeTitle">送车费：</h2>
              <p data-i18n="modalDeliveryFeeText">如果需要送车到清迈或芭提雅，需额外收取 2500 THB。</p>
              <p data-i18n="modalDeliveryFeeDetail">具体送车或异地还车安排，请在下单时与客服确认。</p>
            </section>
            <!-- 其他说明部分 -->
            <section class="policy-section">
              <h2 data-i18n="modalOtherNotesTitle">其他说明：</h2>
              <p data-i18n="modalOtherNotesText">请客户遵守当地交通法规，并在使用过程中妥善保管车辆。</p>
              <p data-i18n="modalOtherNotesDetail">若发生事故或车辆损坏，请第一时间通知客服，我们将协助您进行后续处理。</p>
            </section>
          </div>
          <div class="mb-3">
            <label for="countryCode" class="form-label" data-i18n="modalCountryCode">地区号：</label>
            <select class="form-select" id="countryCode">
              <option value="+86" data-i18n="optionChina">中国 +86</option>
              <option value="+66" data-i18n="optionThailand">泰国 +66</option>
            </select>
          </div>
          <div class="mb-3">
            <label for="userPhone" class="form-label" data-i18n="modalUserPhone">联系电话：</label>
            <input type="text" class="form-control" id="userPhone" placeholder="请输入手机号" data-i18n-placeholder="placeholderPhone"/>
          </div>
          <div class="mb-3">
            <label for="userName" class="form-label" data-i18n="modalUserName">姓名：</label>
            <input type="text" class="form-control" id="userName" placeholder="请输入姓名" data-i18n-placeholder="placeholderName"/>
          </div>
          <div id="modalMsg" style="color: red; margin-top: 5px;"></div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-i18n="modalCancel">取消</button>
          <button type="button" class="btn btn-primary" id="confirmBtn" data-i18n="modalConfirm">确认</button>
        </div>
      </div>
    </div>
  </div>
  <!-- Bootstrap JS -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

  <!-- 业务逻辑脚本 -->
  <script type="module">

    window.zoomImage = function (src) {
      const zoomOverlay = document.getElementById("zoomOverlay");
      const zoomImg = document.getElementById("zoomImage");
      zoomImg.src = src;
      zoomOverlay.style.display = "flex";
    };

    document.getElementById("zoomOverlay").addEventListener("click", function() {
      this.style.display = "none";
    });
    // ========== 多语言相关函数（静态UI翻译） ==========
    async function loadLanguage(lang) {
      try {
        const resp = await fetch(`lang/${lang}.json`);
        return await resp.json();
      } catch (err) {
        console.error("语言文件加载失败:", err);
        return {};
      }
    }
    function applyLanguage(langData) {
      // 替换带 data-i18n 的文字
      document.querySelectorAll("[data-i18n]").forEach(el => {
        const key = el.getAttribute("data-i18n");
        if (langData[key]) {
          el.textContent = langData[key];
        }
      });
      // 替换带 data-i18n-placeholder 的 placeholder
      document.querySelectorAll("[data-i18n-placeholder]").forEach(el => {
        const key = el.getAttribute("data-i18n-placeholder");
        if (langData[key]) {
          el.setAttribute("placeholder", langData[key]);
        }
      });
    }
    function getCurrentLang() {
      return localStorage.getItem("selectedLanguage") || "zh";
    }
    

    // ========== 从 URL 参数获取车辆 JSON ==========
    const urlParams = new URLSearchParams(window.location.search);
    const carDataEncoded = urlParams.get("carData");
    let carID = null; // Firestore 的 doc ID
    let carDailyPrice = 0, carWeeklyPrice = 0, carMonthlyPrice = 0;

    if (carDataEncoded) {
      try {
        const selectedCar = JSON.parse(decodeURIComponent(carDataEncoded));
        // 如果后端传来 "id" 字段，就是 Firestore 文档ID
        carID = selectedCar.id || null;

        // 解析 text：第一行为车名，后几行是价格
        let txt = "";
        if (selectedCar.text) {
          if (typeof selectedCar.text === "string") {
            txt = selectedCar.text;
          } else {
            // 多语言对象
            const lang = getCurrentLang();
            txt = selectedCar.text[lang] || "";
          }
        }
        const lines = txt.split("\n");
        // 第一行：车名
        const carName = lines[0] || "未知车型";
        document.getElementById("carTitle").textContent = carName.trim();

        // 解析价格
        const dailyMatch = lines[1] ? lines[1].match(/(\d+)/) : null;
        const weeklyMatch = lines[2] ? lines[2].match(/(\d+)/) : null;
        const monthlyMatch = lines[3] ? lines[3].match(/(\d+)/) : null;
        carDailyPrice = dailyMatch ? parseInt(dailyMatch[1]) : 0;
        carWeeklyPrice = weeklyMatch ? parseInt(weeklyMatch[1]) : 0;
        carMonthlyPrice = monthlyMatch ? parseInt(monthlyMatch[1]) : 0;
        document.getElementById("dailyPrice").textContent = carDailyPrice || "---";
        document.getElementById("weeklyPrice").textContent = carWeeklyPrice || "---";
        document.getElementById("monthlyPrice").textContent = carMonthlyPrice || "---";

        // 图片
        const coverImg = (selectedCar.images && selectedCar.images.length > 0)
          ? selectedCar.images[0]
          : "https://via.placeholder.com/400";
       

        // 描述
        if (selectedCar.description) {
          let desc = "";
          if (typeof selectedCar.description === "string") {
            desc = selectedCar.description;
          } else {
            const lang = getCurrentLang();
            desc = selectedCar.description[lang] || "";
          }
          document.getElementById("carDetail").textContent = desc;
        }
        renderDetailCarImages(selectedCar);
      } catch (e) {
        console.error("解析 carData 失败:", e);
      }
    } else {
      console.log("URL 中没有传入 carData");
    }

    function isOverlapping(newStart, newEnd, booked) {
      const bookedStart = new Date(booked.from);
      const bookedEnd = new Date(booked.to);
      // 将已预订区间设定为当天 00:00 ~ 23:59
      bookedStart.setHours(0, 0, 0, 0);
      bookedEnd.setHours(23, 59, 59, 999);
  
      // 如果新区间 [newStart, newEnd] 和已预订区间 [bookedStart, bookedEnd] 有交集，则返回 true
      // 两个区间相交的条件是：新开始 <= 已预订结束 && 新结束 >= 已预订开始
      return newStart <= bookedEnd && newEnd >= bookedStart;
    }

    function calculateExtraPrice(days) {
      if (days <= 7) {
        // 日均价格从 carDailyPrice 线性递减到 (carWeeklyPrice / 7)
        let dailyAvg = carDailyPrice - ((carDailyPrice - (carWeeklyPrice / 7)) * (days - 1)) / 6;
        return dailyAvg * days;
      } else if (days <= 17) {
        // 日均价格从 (carWeeklyPrice / 7) 线性递减到 (carMonthlyPrice / 25)
        let dailyAvg = (carWeeklyPrice / 7) - (((carWeeklyPrice / 7) - (carMonthlyPrice / 17)) * (days - 7)) / 10;
        return dailyAvg * days;
      } else {
        // 25～30天内，价格固定为 carMonthlyPrice
        return carMonthlyPrice;
      }
    }

    function calculateTotalPrice(totalDays) {
      let fullCycles = Math.floor(totalDays / 30);  // 完整 30 天周期的个数
      let remainder = totalDays % 30;               // 余下天数
      let totalPrice = fullCycles * carMonthlyPrice;  // 每个周期固定 carMonthlyPrice
      if (remainder > 0) {
        totalPrice += calculateExtraPrice(remainder);
      }
      return totalPrice;
    }

    // ========== 租车天数与价格计算 ==========
    function updatePrice() {
      const startVal = document.getElementById("startDate").value;
      const endVal = document.getElementById("endDate").value;
      const daysEl = document.getElementById("daysInfo");
      const priceEl = document.getElementById("priceInfo");
      const depositEl = document.getElementById("depositInfo");
      const statusMsg = document.getElementById("statusMsg");

      if (!startVal || !endVal) {
        daysEl.textContent = 0;
        priceEl.textContent = 0;
        depositEl.textContent = 0; // 无日期时押金也置 0
        statusMsg.textContent = "";
        return;
      }
      const startDate = new Date(startVal);
      const endDate = new Date(endVal);
      if (endDate <= startDate) {
        daysEl.textContent = 0;
        priceEl.textContent = 0;
        depositEl.textContent = 0;
        statusMsg.style.color = "red";
        statusMsg.textContent = currentLangData["errDateInvalid"] || "还车日期必须大于取车日期。";
        document.getElementById("nextBtn").disabled = true;
        return;
      } else {
        statusMsg.textContent = "";
        document.getElementById("nextBtn").disabled = false;
      }
      const diffTime = endDate - startDate;
      const n = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      daysEl.textContent = n;

      const rentalPriceRaw = calculateTotalPrice(n);
      const rentalPrice = Math.round(rentalPriceRaw / 100) * 100;
      priceEl.textContent = rentalPrice;
  
      let depositVal;
      if (n <= 7) {
        const d = carDailyPrice;
        if      (d <= 2000) depositVal = 5000;
        else if (d <= 3000) depositVal = 6000;
        else if (d <= 4000) depositVal = 6500;
        else if (d <= 5000) depositVal = 7000;
        else if (d <= 6000) depositVal = 8000;
        else if (d <= 7000) depositVal = 9000;
        else                 depositVal = 9000;
      } else {
        // 第八天以后押金＝租金总额
        depositVal = rentalPrice;
      }
      depositEl.textContent = depositVal;
      
    }
    document.getElementById("startDate").addEventListener("change", updatePrice);
    document.getElementById("endDate").addEventListener("change", updatePrice);
    // ========== Modal 显示时同步数据 ==========
    const nextBtn = document.getElementById("nextBtn");
    nextBtn.addEventListener("click", (evt) => {
      const startVal = document.getElementById("startDate").value;
      const endVal = document.getElementById("endDate").value;
      const daysText = document.getElementById("daysInfo").textContent;
      const priceText = document.getElementById("priceInfo").textContent;
      const depositText = document.getElementById("depositInfo").textContent;
      if (!startVal || !endVal) {
        alert(currentLangData["errFillDate"] || "请先选择取车和还车日期！");
        evt.preventDefault();
        return;
      }
      if (daysText === "0" || daysText === "日期错误") {
        alert(currentLangData["errDateInvalid"] || "请先选择正确的日期再点击下一步！");
        evt.preventDefault();
        return;
      }

      const newStart = new Date(startVal);
      const newEnd   = new Date(endVal);
  
      // 如果你在 getBookedRanges 的 then(...) 里把 bookedRanges 存到了 window.bookedRanges
      const hasOverlap = window.bookedRanges && window.bookedRanges.some(range =>
        isOverlapping(newStart, newEnd, range)
      );
  
      if (hasOverlap) {
        statusMsg.style.color = "red";
        statusMsg.textContent = currentLangData["errDateOverlap"] || "日期重叠，请选择其他日期。";
        evt.preventDefault();  // 阻止进入 Modal
        return;
      }
      document.getElementById("modalDays").textContent = daysText;
      document.getElementById("modalPrice").textContent = priceText;
      document.getElementById("modalDeposit").textContent = depositText;
      document.getElementById("modalMsg").textContent = "";
    });

    // ========== 电话号码验证函数 ==========
    function validatePhoneNumber(phone, countryCode) {
      const cleaned = phone.replace(/\D/g, "");
      if (countryCode === "+86") {
        return /^\d{11}$/.test(cleaned);
      } else if (countryCode === "+66") {
        return /^\d{9}$/.test(cleaned);
      }
      return false;
    }

    function renderDetailCarImages(car) {
      const container = document.getElementById("carImagesContainer");
      if (!car.images || car.images.length === 0) {
        container.innerHTML = "";
        return;
      }
      // 把 images 数组里的 URL 全部拼成 <img>，Grid 会排两列
      container.innerHTML = car.images.map((url, i) => `
        <img
          src="${url}"
          alt="车辆图片 ${i+1}"
          onclick="zoomImage(this.src)"
        >
      `).join("");
    }

    // ========== 提交订单 ========== 
    import { initializeApp as initializeApp2 } from "https://www.gstatic.com/firebasejs/9.22.2/firebase-app.js";
    import { getFirestore as getFirestore2, collection, addDoc, serverTimestamp } from "https://www.gstatic.com/firebasejs/9.22.2/firebase-firestore.js";

    const firebaseConfig2 = {
      apiKey: "YOUR_API_KEY",
      authDomain: "rental-7fe8c.firebaseapp.com",
      projectId: "rental-7fe8c",
      storageBucket: "rental-7fe8c.firebasestorage.app",
      messagingSenderId: "263132536954",
      appId: "1:263132536954:web:55d988d88b1a078b4b9bc3"
    };
    const appFB = initializeApp2(firebaseConfig2);
    const dbFB = getFirestore2(appFB);

    const confirmBtn = document.getElementById("confirmBtn");
    confirmBtn.addEventListener("click", async () => {
      const modalMsg = document.getElementById("modalMsg");
      const daysText = document.getElementById("modalDays").textContent;
      const priceText = document.getElementById("modalPrice").textContent;
      const depositText = document.getElementById("modalDeposit").textContent;
      const userName = document.getElementById("userName").value.trim();
      const userPhone = document.getElementById("userPhone").value.trim();
      const countryCode = document.getElementById("countryCode").value;
      const startVal = document.getElementById("startDate").value;
      const endVal = document.getElementById("endDate").value;
      const newStart = new Date(startVal);
      const newEnd = new Date(endVal);

      if (!userName || !userPhone || !startVal || !endVal) {
        modalMsg.textContent = currentLangData["errFillAll"] || "请填写完整信息后再提交。";
        return;
      }
      if (newEnd <= newStart) {
        modalMsg.textContent = currentLangData["errDateInvalid"] || "还车日期必须大于取车日期。";
        return;
      }
      if (!validatePhoneNumber(userPhone, countryCode)) {
        modalMsg.textContent = currentLangData["errInvalidPhone"] || "请输入有效的电话号码（中国11位或泰国9位）。";
        return;
      }
      const overlapping = window.bookedRanges && window.bookedRanges.some(range => isOverlapping(newStart, newEnd, range));
      if (overlapping) {
        modalMsg.textContent = "您选择的日期与已有预订重叠，请选择其他日期。";
        return;
      }
      
      const orderId = Date.now().toString();
      try {
        // 这里使用上面解析出来的全局 carID
        const orderData = {
          orderId: orderId,
          name: userName,
          phone: countryCode + userPhone,
          startDate: startVal,
          endDate: endVal,
          days: daysText,
          rentalPrice: priceText,
          carId: carID, // Firestore 文档 ID
          deposit: depositText,
          carName: document.getElementById("carTitle").textContent,
          createdAt: serverTimestamp()
        };
        
        const docRef = await addDoc(collection(dbFB, "orders"), orderData);
        console.log("真实的文档ID:", docRef.id);
        window.location.href = "pay.html?orderId=" + docRef.id;;
      } catch (error) {
        console.error("提交失败：", error);
        modalMsg.textContent = "提交失败，请稍后重试。";
      }
    });

    // ========== 多语言加载 ==========
    let currentLangData = {};
    async function initLanguage() {
      const currentLang = getCurrentLang();
      currentLangData = await loadLanguage(currentLang);
      applyLanguage(currentLangData);
    }
    window.addEventListener("DOMContentLoaded", async () => {
      await initLanguage();
    });

    // ========== Flatpickr 初始化（标红预订日期） ==========
    import { collection as col2, query as q2, where as w2, getDocs as getDocs2 } from "https://www.gstatic.com/firebasejs/9.22.2/firebase-firestore.js";
    async function getBookedRanges(carId) {
      if (!carId) return [];
      const q = q2(col2(dbFB, "orders"), w2("carId", "==", carId));
      const querySnapshot = await getDocs2(q);
      const ranges = [];
      querySnapshot.forEach(docSnap => {
        const data = docSnap.data();
        ranges.push({ from: data.startDate, to: data.endDate });
      });
      return ranges;
    }

    // 如果 carID 不为空，则查询已预订日期
    if (carID) {
      getBookedRanges(carID).then(bookedRanges => {
        window.bookedRanges = bookedRanges || [];
        const currentLang = getCurrentLang();
        const flatLocale = currentLang === "zh"
          ? flatpickr.l10ns.zh
          : (currentLang === "th" ? flatpickr.l10ns.th : "en");

        flatpickr("#startDate", {
          dateFormat: "Y-m-d",
          minDate: "today",
          maxDate: "2030-12-31",
          disable: bookedRanges,
          locale: flatLocale,
          onDayCreate: function(dObj, dStr, fp, dayElem) {
            bookedRanges.forEach(range => {
              const fromDate = new Date(range.from);
              const toDate = new Date(range.to);
              fromDate.setHours(0, 0, 0, 0);
              toDate.setHours(23, 59, 59, 999);
              if (dayElem.dateObj >= fromDate && dayElem.dateObj <= toDate) {
                dayElem.classList.add("booked-day");
                dayElem.title = "已预订";
              }
            });
          }
        });

        flatpickr("#endDate", {
          dateFormat: "Y-m-d",
          minDate: "today",
          maxDate: "2030-12-31",
          locale: flatLocale,
          disable: bookedRanges,
          onDayCreate: function(dObj, dStr, fp, dayElem) {
            bookedRanges.forEach(range => {
              const fromDate = new Date(range.from);
              const toDate = new Date(range.to);
              fromDate.setHours(0, 0, 0, 0);
              toDate.setHours(23, 59, 59, 999);
              if (dayElem.dateObj >= fromDate && dayElem.dateObj <= toDate) {
                dayElem.classList.add("booked-day");
                dayElem.title = "已预订";
              }
            });
          }
        });
      });
    }
  </script>
</body>
</html>